import type { FormInstance } from 'element-plus'
import type { loginStateType, loginParamsType } from './typings'
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElButton,
  ElLink,
  ElIcon
  // ElImage
} from 'element-plus'
import {
  User,
  Lock,
  View,
  Hide
  // Key
} from '@element-plus/icons-vue'
import styles from './index.module.scss'

export default defineComponent(function Login() {
  // 获取vuex的store
  const store = useStore()
  // 获取路由对象做跳转操作
  const router = useRouter()
  const ruleFormRef = ref<FormInstance>()
  const state = reactive<loginStateType>({
    passwordType: 'password',
    image: '',
    submitting: false
  })
  const loginValidateForm = reactive<loginParamsType>({
    account: '',
    password: '',
    grantType: 'captcha'
  })

  // 切换展示密码
  const handleChoosePasswordType = () => {
    state.passwordType = state.passwordType === 'text' ? 'password' : 'text'
  }

  // 获取验证码
  const handleRefreshCaptcha = () => {
    store.dispatch('user/GetCaptcha').then((res) => {
      state.image = res.image
      // 将key赋值给表单
      loginValidateForm.key = res.key
    })
  }
  // 提交登录表单
  const handleSubmitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid) => {
      if (!valid) return false
      // 设置登录按钮加载中
      state.submitting = true
      const res = await store.dispatch('user/LoginByUsername', loginValidateForm as loginParamsType)
      // 关闭登录按钮加载中
      state.submitting = false
      if (res) router.push(store.getters['tags/tag']?.value || '/home')
    })
  }

  // 按回车提交表单
  const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
    if ((evt as KeyboardEvent).key === 'Enter') handleSubmitForm(ruleFormRef.value)
  }

  onMounted(() => {
    handleRefreshCaptcha()
  })

  return () => (
    <ElForm class={styles['login-form']} size="large" ref={ruleFormRef} model={loginValidateForm}>
      <ElFormItem prop="account" rules={[{ required: true, message: '请输入用户名' }]}>
        <ElInput
          v-model={loginValidateForm.account}
          type="text"
          autocomplete="on"
          placeholder="请输入账号"
          onKeydown={handleKeyDownEnterSubmitForm}
        >
          {{
            prefix: () => (
              <ElLink type="primary" underline={false}>
                <ElIcon class="el-input__icon">
                  <User />
                </ElIcon>
              </ElLink>
            )
          }}
        </ElInput>
      </ElFormItem>
      <ElFormItem prop="password" rules={[{ required: true, message: '请输入密码' }]}>
        <ElInput
          v-model={loginValidateForm.password}
          type={state.passwordType}
          autocomplete="off"
          placeholder="请输入密码"
          onKeydown={handleKeyDownEnterSubmitForm}
        >
          {{
            prefix: () => (
              <ElLink type="primary" underline={false}>
                <ElIcon class="el-input__icon">
                  <Lock />
                </ElIcon>
              </ElLink>
            ),
            suffix: () => (
              <ElLink
                class={styles['el-input-password-icon']}
                type="primary"
                underline={false}
                onClick={handleChoosePasswordType}
              >
                <ElIcon class="el-input__icon">
                  {state.passwordType === 'text' ? <View /> : <Hide />}
                </ElIcon>
              </ElLink>
            )
          }}
        </ElInput>
      </ElFormItem>
      {/* <ElFormItem prop="code" rules={[{ required: true, message: '请输入验证码' }]}>
        <ElInput
          v-model={loginValidateForm.code}
          placeholder="请输入验证码"
          onKeydown={handleKeyDownEnterSubmitForm}
        >
          {{
            prefix: () => (
              <ElLink type="primary" underline={false}>
                <ElIcon class="el-input__icon">
                  <Key />
                </ElIcon>
              </ElLink>
            ),
            append: () => (
              <a onClick={handleRefreshCaptcha}>
                <ElImage class={styles['login-verification-code']} src={state.image} fit="fill" />
              </a>
            )
          }}
        </ElInput>
      </ElFormItem> */}
      <ElFormItem prop="key" class="hidden-form-item">
        <ElInput type="hidden" v-model={loginValidateForm.key} />
      </ElFormItem>
      <ElFormItem prop="grantType" class="hidden-form-item">
        <ElInput type="hidden" v-model={loginValidateForm.grantType} />
      </ElFormItem>
      <ElFormItem>
        <ElButton
          class={styles['login-form-submit-btn']}
          type="primary"
          loading={state.submitting}
          onClick={() => handleSubmitForm(ruleFormRef.value)}
        >
          登录
        </ElButton>
      </ElFormItem>
    </ElForm>
  )
})
